import { _decorator, resources, Asset, AudioClip, assetManager, AssetManager } from "cc";
const { ccclass, property } = _decorator;

export class ResourceManager {
    private static _instance: ResourceManager;

    static getInstance() {
        if (!this._instance) {
            this._instance = new ResourceManager();
        }

        return this._instance;
    }

    constructor() {}

    /**
     * 根据路径加载资源
     * @param path 资源路径
     * @returns
     */
    public async loadPath<T extends Asset>(path: string): Promise<T> {
        return new Promise((resolve, reject) => {
            resources.load<T>(path, (error, resource) => {
                if (error) {
                    reject(error);
                    return;
                }
                // Logger.log(path, resources);
                resolve(resource);
                return;
            });
        });
    }

    /**
     * 加载资源文件夹
     */
    public async loadDir<T extends Asset>(path: string): Promise<T[]> {
        return new Promise((resolve, reject) => {
            resources.loadDir<T>(path, (error, resource) => {
                if (error) {
                    reject(error);
                    return;
                }
                resolve(resource);
                return;
            });
        });
    }

    /**
     * 加载音频文件
     * @param url
     * @param callback
     */
    public async loadAudio(audioPath: string): Promise<AudioClip> {
        return new Promise((resolve, reject) => {
            resources.load(audioPath, AudioClip, (error: Error | null, resource: AudioClip) => {
                if (error) {
                    reject(error);
                    return;
                }
                resolve(resource);
                return;
            });
        });
    }

    /**
     * 加载远程资源
     * @param remoteUrl
     * @returns
     */
    public async loadRemote(remoteUrl: string) {
        return new Promise((resolve, reject) => {
            assetManager.loadRemote(remoteUrl, (error, resource) => {
                if (!error) {
                    resolve(resource);
                } else {
                    reject(error);
                }
            });
        });
    }

    /**
     * 获取已加载资源
     * @param path
     * @param type
     * @param bundleName
     * @returns
     */
    public get<T extends Asset>(path: string, bundleName: string = "resources"): T | null {
        const bundle: AssetManager.Bundle | null = assetManager.getBundle(bundleName);
        return bundle!.get(path);
    }
}
